package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainBatchLinkItemDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.pro.message.model.PushLinkModel;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.pushnotify.dto.PushNotifyDeleteDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PushNotifyEnum;
import com.xbongbong.saas.enums.business.RefTypeEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.service.ContactService;
import com.xbongbong.saas.service.PushNotifyService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/3/26 19:38
 * @since v1.0
 */
@Service("pushNotifyService")
public class PushNotifyServiceImpl implements PushNotifyService {
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private PushModel pushModel;
    @Resource
    private PushLinkModel pushLinkModel;
    @Resource
    private ContactModel contactModel;

    /**
     * 关联新建时格式化解释
     *
     * @param handlerExplainInLinkItemDTO 入参
     * @throws XbbException 异常
     * @author feng.zheng
     * @date 2019-03-16 20:53
     */
    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
        PaasFormDataEntityExt paasFormDataEntityExt = handlerExplainInLinkItemDTO.getPaasFormDataEntityExt();
        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
        Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId();
        FieldAttrEntity titleField = new FieldAttrEntity();
        FieldAttrEntity nameField = new FieldAttrEntity();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.TITLE.getAttr())) {
                titleField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.NOTIFY_NAME.getAttr())) {
                nameField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.NOTIFY_TIME.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.COMMUNICATE_TIME.getAttr())) {
                // 提醒时间和跟进时间只能选未来时间，所以限制昨天及之前的日期不能选
                SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                saasParticularAttributePoJo = saasParticularAttributePoJo == null ? new SaasParticularAttributePoJo() : saasParticularAttributePoJo;
                saasParticularAttributePoJo.setDateLimit(DateTimeUtil.getTodayInt(DateTimeUtil.getInt()) - BasicConstant.ONE);
                saasParticularAttributePoJo.setLimitType(false);
                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
            }
        }
        Integer linkBusinessType = handlerExplainInLinkItemDTO.getLinkBusinessType();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(linkBusinessType);
        if (Objects.equals(RedundantTemplateTypeEnum.PURCHASE, redundantTemplateTypeEnum) ||
                Objects.equals(RedundantTemplateTypeEnum.SUPPLIER, redundantTemplateTypeEnum)
                || Objects.equals(RedundantTemplateTypeEnum.CLUE, redundantTemplateTypeEnum)) {
            explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.ENTER_COMMUNICATE_PLAN.getAttr()));
        }
        String serialNo = paasFormDataEntityExt.getSerialNo() == null ? "" : paasFormDataEntityExt.getSerialNo();
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                String customerName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, CustomerManagementEnum.NAME.getAttr(), "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(customerName + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(CustomerManagementEnum.NAME.getAttrName());
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, customerName, linkBusinessType));
                nameField.setLinkedType(RedundantTemplateTypeEnum.CUSTOMER.getCode());
                break;
            case CONTACT:
                // 联系人跟进提醒本质上还是客户提醒，只是在联系人上开了一个口子
                String corpid = paasFormDataEntityExt.getCorpid();
                ContactEntityExt contactEntityExt = contactModel.getByKey(linkDataId, corpid);
                JSONObject data = contactEntityExt.getData();
                String linkCustomerId = FastJsonHelper.getStringOrDefault(data, ContactEnum.CUSTOMER_NAME.getAttr(), "");
                if (StringUtils.isEmpty(linkCustomerId)) {
                    break;
                }
                String linkCustomer = FastJsonHelper.getStringOrDefault(data, ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(linkCustomer + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(CustomerManagementEnum.NAME.getAttrName());
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(Long.valueOf(linkCustomerId), linkCustomer, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()));
                nameField.setLinkedType(RedundantTemplateTypeEnum.CUSTOMER.getCode());
                break;
            case CONTRACT:
                String contractName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, ContractEnum.NAME.getAttr(), "");
                if (!contractName.isEmpty()) {
                    serialNo += "("  + contractName + ")";
                }
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(serialNo + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(RefTypeEnum.CONTRACT.getName());
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, serialNo, linkBusinessType));
                nameField.setLinkedType(RedundantTemplateTypeEnum.CONTRACT.getCode());
                break;
            case SALES_OPPORTUNITY:
                String opportunityName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SalesOpportunityEnum.NAME.getAttr(), "");
                if (!opportunityName.isEmpty()) {
                    serialNo += "("  + opportunityName + ")";
                }
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(serialNo + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(ContractEnum.LINK_OPPORTUNITY.getAttrName());
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, serialNo, linkBusinessType));
                nameField.setLinkedType(RedundantTemplateTypeEnum.SALES_OPPORTUNITY.getCode());
                break;
            case SUPPLIER:
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(supplierName + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(SupplierEnum.SUPPLIER_NAME.getAttrName());
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, supplierName, linkBusinessType));
                nameField.setLinkedType(RedundantTemplateTypeEnum.SUPPLIER.getCode());
                break;
            case PURCHASE:
                String purchaseNo = paasFormDataEntityExt.getSerialNo();
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(purchaseNo + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(PurchaseEnum.SHEET_NO.getAttrName());
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, purchaseNo, linkBusinessType));
                nameField.setLinkedType(RedundantTemplateTypeEnum.PURCHASE.getCode());
                break;
            case QUOTATION:
                String quotationNo = paasFormDataEntityExt.getSerialNo();
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(quotationNo + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(I18nMessageUtil.getMessage(CommonConstant.NAME));
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, quotationNo, linkBusinessType));
                nameField.setLinkedType(RedundantTemplateTypeEnum.QUOTATION.getCode());
                break;
            case CLUE:
                String clueName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, ClueEnum.COMPANY_NAME.getAttr(), "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(clueName + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(I18nMessageUtil.getMessage(CommonConstant.NAME));
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, clueName, linkBusinessType));
                nameField.setLinkedType(RedundantTemplateTypeEnum.CLUE.getCode());
                break;
            case COMMUNICATE_PLAN:
                JSONArray linkCustomerNameArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData, CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), new JSONArray());
                if (CollectionUtils.isNotEmpty(linkCustomerNameArray)){
                    //获取访客计划关联客户的id
                    JSONObject jsonObject = (JSONObject) linkCustomerNameArray.get(0);
                    linkDataId = FastJsonHelper.getLongOrDefaultFromFormData(jsonObject,"id",0L);
                }
                String linkCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(linkCustomerNameArray.getJSONObject(0), StringConstant.SAAS_LINK_BUSINESS_NAME, "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(linkCustomerName + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(CommunicatePlanEnum.LINK_CUSTOMER.getAttrName());
                nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, linkCustomerName, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()));
                nameField.setLinkedType(RedundantTemplateTypeEnum.COMMUNICATE_PLAN.getCode());
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
    }

    @Override
    public void deletePushNotify(PushNotifyDeleteDTO pushNotifyDeleteDTO) throws XbbException {
        List<Long> notifyIdList = new ArrayList<>();
        List<PushEntity> pushNotifyList = pushModel.getPushNotify(pushNotifyDeleteDTO.getNeedDelNotifyIdList(), pushNotifyDeleteDTO.getCorpid(), pushNotifyDeleteDTO.getBusinessType(), notifyIdList);
        if (!pushNotifyList.isEmpty()) {
            List<Long> pushIds = new ArrayList<>();
            pushNotifyList.forEach(pushEntity -> pushIds.add(pushEntity.getId()));
            if (!pushIds.isEmpty()) {
                pushModel.deleteByIdIn(pushIds, pushNotifyDeleteDTO.getCorpid());
                pushLinkModel.deleteByPushIdIn(pushIds, pushNotifyDeleteDTO.getCorpid());
            }
        }
    }

    @Override
    public void formatBatchLinkAddExplain(HandlerExplainBatchLinkItemDTO handlerExplainBatchLinkItemDTO) throws XbbException {
        List<FieldAttrEntity> explainList = handlerExplainBatchLinkItemDTO.getExplainList();
        List<PaasFormDataEntityExt> paasFormDataEntityExts = handlerExplainBatchLinkItemDTO.getPaasFormDataEntityExts();
        Integer size = paasFormDataEntityExts.size();
        PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataEntityExts.get(BasicConstant.ZERO);
        JSONObject linkFormData = paasFormDataEntityExt.getData();
        FieldAttrEntity titleField = new FieldAttrEntity();
        FieldAttrEntity nameField = new FieldAttrEntity();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.TITLE.getAttr())) {
                titleField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.NOTIFY_NAME.getAttr())) {
                nameField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.NOTIFY_TIME.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.COMMUNICATE_TIME.getAttr())) {
                // 提醒时间和跟进时间只能选未来时间，所以限制昨天及之前的日期不能选
                SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                saasParticularAttributePoJo = saasParticularAttributePoJo == null ? new SaasParticularAttributePoJo() : saasParticularAttributePoJo;
                saasParticularAttributePoJo.setDateLimit(DateTimeUtil.getTodayInt(DateTimeUtil.getInt()) - BasicConstant.ONE);
                // limitType为fales表示限制之前日期不能选
                saasParticularAttributePoJo.setLimitType(false);
                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
            }
        }
        Integer linkBusinessType = handlerExplainBatchLinkItemDTO.getLinkBusinessType();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(linkBusinessType);
        if (Objects.equals(RedundantTemplateTypeEnum.PURCHASE, redundantTemplateTypeEnum) ||
                Objects.equals(RedundantTemplateTypeEnum.SUPPLIER, redundantTemplateTypeEnum)
                || Objects.equals(RedundantTemplateTypeEnum.CLUE, redundantTemplateTypeEnum)) {
            explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), PushNotifyEnum.ENTER_COMMUNICATE_PLAN.getAttr()));
        }
        JSONArray nameArray = new JSONArray();
        for (PaasFormDataEntityExt formData : paasFormDataEntityExts) {
            JSONObject dataList = new JSONObject();
            dataList.put(StringConstant.SAAS_LINK_BUSINESS_ID, formData.getId());
            if (RedundantTemplateTypeEnum.PURCHASE.equals(redundantTemplateTypeEnum) || RedundantTemplateTypeEnum.QUOTATION.equals(redundantTemplateTypeEnum) || RedundantTemplateTypeEnum.CONTRACT.equals(redundantTemplateTypeEnum)) {
                dataList.put(StringConstant.SAAS_LINK_BUSINESS_NAME, formData.getSerialNo());
            } else {
                dataList.put(StringConstant.SAAS_LINK_BUSINESS_NAME, FastJsonHelper.getStringOrDefaultFromFormData(formData.getData(), CustomerManagementEnum.NAME.getAttr(), ""));
            }
            dataList.put(StringConstant.BUSINESS_TYPE, linkBusinessType);
            nameArray.add(dataList);
        }
        String serialNo = paasFormDataEntityExt.getSerialNo() == null ? "" : paasFormDataEntityExt.getSerialNo();
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                String customerName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, CustomerManagementEnum.NAME.getAttr(), "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_ETC), customerName, size) + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(CustomerManagementEnum.NAME.getAttrName());
                break;
            case CONTRACT:
                String contractName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, ContractEnum.NAME.getAttr(), "");
                if (!contractName.isEmpty()) {
                    serialNo += "("  + contractName + ")";
                }
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.CONTRACT_ETC), serialNo, size) + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(RefTypeEnum.CONTRACT.getName());
                break;
            case SALES_OPPORTUNITY:
                String opportunityName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SalesOpportunityEnum.NAME.getAttr(), "");
                if (!opportunityName.isEmpty()) {
                    serialNo += "("  + opportunityName + ")";
                }
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.OPPORTUNITY_ETC), serialNo, size) + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(ContractEnum.LINK_OPPORTUNITY.getAttrName());
                break;
            case SUPPLIER:
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.SUPPLIER_ETC), supplierName, size) + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(SupplierEnum.SUPPLIER_NAME.getAttrName());
                break;
            case PURCHASE:
                String purchaseNo = paasFormDataEntityExt.getSerialNo();
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.PURCHASE_ETC), purchaseNo, size) + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(PurchaseEnum.SHEET_NO.getAttrName());
                break;
            case QUOTATION:
                String quotationNo = paasFormDataEntityExt.getSerialNo();
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.QUOTATION_ETC), quotationNo, size) + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(I18nMessageUtil.getMessage(CommonConstant.NAME));
                break;
            case CLUE:
                String clueName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, ClueEnum.COMPANY_NAME.getAttr(), "");
                titleField.setDefaultAttr(saasUpdateHelp.setDefaultValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.CLUE_ETC), clueName, size) + I18nMessageUtil.getMessage(StringConstant.NOTIFY)));
                nameField.setAttrName(ClueEnum.COMPANY_NAME.getAttrName());
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        nameField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(nameArray));
    }
}
